<template>
  <!--通知公告列表-->
  <div class="app-container">
    <!-- 顶部表单部分 -->
    <div class="form-container">
      <el-form ref="formNotice" :model="filters" :inline="true" label-width="80px">
        <el-form-item label="公告标题" prop="noticeTitle">
          <el-input
            v-model="filters.noticeTitle"
            placeholder="请输入公告标题"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item v-if="isStatus" label="公告状态" prop="status">
          <el-select v-model="filters.status" placeholder="请输入公告状态" clearable size="small">
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="dateRange">
          <el-date-picker
            v-model="dateRange"
            size="small"
            style="width:225px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="false"
          />
        </el-form-item>
      </el-form>
    </div>
    <!--操作按钮-->
    <div class="btns-group">
      <el-button v-clickForbidden icon="el-icon-search" size="middle" @click="handleQuery">搜索</el-button>
      <el-button v-clickForbidden icon="el-icon-refresh" size="middle" @click="resetQuery">重置</el-button>
      <!-- 功能按钮部分  -->
      <el-button v-hasPermi="['system:notice:add']" icon="el-icon-plus" size="middle" @click="handleAdd">新增</el-button>
      <el-button v-hasPermi="['system:notice:edit']" icon="el-icon-edit" size="middle" :disabled="isAmend" @click="handleUpdate">修改</el-button>
      <el-button v-hasPermi="['system:notice:delete']" icon="el-icon-delete" size="middle" :disabled="isAmend" @click="handleDelete">删除</el-button>
      <el-button v-hasPermi="['system:notice:detail']" icon="el-icon-zoom-in" size="middle" :disabled="isAmend" @click="handleDetail">详情</el-button>
      <el-button v-hasPermi="['system:notice:changeStatus']" icon="el-icon-setting" size="middle" :disabled="isAmend" @click="handleStatus">变更状态</el-button>
    </div>
    <!-- 表格数据部分 -->
    <el-table
      ref="multipleTable"
      :row-style="rowClass"
      :class="highLevelSet===true ? (needTagsView===true ? 'el-body-page-roll-tag-height' : 'el-body-page-roll-height') :
        (needTagsView===true ? 'el-body-page-roll-tag' : 'el-body-page-roll')"
      class="table-list"
      stripe
      :data="noticeList"
      @selection-change="handleSelectionChange"
      @row-click="rowChecked"
    >
      <el-table-column type="selection" width="38" align="center" />
      <el-table-column label="序号" align="center" type="index" width="60" />
      <el-table-column label="公告标题" align="center" min-width="200" prop="noticeTitle" :show-overflow-tooltip="true" />
      <el-table-column v-if="isStatus" label="公告状态" align="center" prop="status" min-width="80">
        <template slot-scope="scope" :formatter="statusFormat">
          <span v-if="scope.row.status=== '0'">正常</span>
          <span v-if="scope.row.status=== '1'">关闭</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="180" /> -->
      <el-table-column label="创建者" align="center" prop="createName" min-width="80" />
    </el-table>
    <pagination
      :total="total"
      :page.sync="filters.pageNum"
      :limit.sync="filters.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { getEnterpriseType } from '@/utils/auth'
import { mapState } from 'vuex'
import { listNotice, delNotice, updateNoticeStatus } from '@/api/PersonalOffice/notice'
export default {
  name: 'Notice',
  components: {
  },
  data() {
    return {
      // 高亮数组
      selectRow: [],
      // 高级设置显示隐藏
      highLevelSet: false,
      // 修改按钮是否可用
      isAmend: true,
      // 删除按钮是否可用
      isDelete: true,
      // 选中数组
      ids: [],
      // 选中的行对象
      multipleSelection: [],
      // 顶部表单数据
      filters: {
        pageNum: 1,
        pageSize: 20,
        noticeTitle: '',
        status: ''
      },
      loading: false, // 列表加载
      total: 1, // 分页总条数
      // 时间范围数组
      dateRange: [],
      // 通知状态
      statusOptions: [],
      // 通知类型
      typeOptions: [],
      // 表格数据
      noticeList: []
    }
  },
  computed: {
    ...mapState({
      needTagsView: state => state.settings.tagsView,
      userInfo: state => state.user.userInfo
    }),
    isStatus() {
      const { enterpriseId, subCompany } = this.userInfo
      return getEnterpriseType() === '1' && enterpriseId === subCompany
    }

  },
  created() {
    this.getList()
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data.rows
    })
    this.getDicts('sys_notice_type').then(response => {
      this.typeOptions = [{ dictValue: '', dictLabel: '全部' }, ...response.data.rows]
    })
    this.getDicts('sys_notice_status').then(response => {
      this.statusOptions = [{ dictValue: '', dictLabel: '全部' }, ...response.data.rows]
    })
  },
  methods: {
    // 通知公告状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.noticeType)
    },
    // 单击每行时每行的复选框选中
    rowChecked(row) {
      const selectData = this.multipleSelection
      this.$refs.multipleTable.clearSelection()
      if (selectData.length === 1) {
        selectData.forEach((item) => {
          // 判断 如果当前的一行被勾选, 再次点击的时候就会取消选中
          if (item === row) {
            this.$refs.multipleTable.toggleRowSelection(row, false)
          } else {
            this.$refs.multipleTable.toggleRowSelection(row, true)
          }
        })
      } else {
        this.$refs.multipleTable.toggleRowSelection(row, true)
      }
    },

    // 获取列表数据
    async getList() {
      const { data: { rows, total }} = await listNotice(this.changeDateRange(this.filters, this.dateRange))
      this.noticeList = rows
      this.total = total
      // this.addTaleData()
    },
    // 填充空白行
    addTaleData() {
      if (this.noticeList.length < 20) {
        const arr = {}
        this.noticeList.push(arr)
        this.addTaleData()
      }
    },
    // 复选框选择
    // 点击表格前面选框时触发的事件
    handleSelectionChange(val) {
      if (JSON.stringify(val[0]) === '{}') {
        this.$refs.multipleTable.clearSelection()
        val = []
      }
      if (val.length === 1) {
        this.isAmend = false
      } else {
        this.isAmend = true
      }
      this.selectRow = []
      this.multipleSelection = val
      if (this.multipleSelection.length > 0) {
        this.multipleSelection.forEach((item, index) => {
          this.selectRow.push(this.noticeList.indexOf(item))
        })
      }
      if (val.length > 1) {
        this.$refs.multipleTable.clearSelection()
        this.$refs.multipleTable.toggleRowSelection(val.pop())
      }
    },
    // select(se) {
    //   this.isAmend = se.length !== 1
    //   this.isDelete = se.length <= 0
    //   this.multipleSelection = se
    //   this.ids = se.map(item => item.noticeId)
    //   // 表格高亮
    //   this.selectRow = []
    //   if (se.length > 0) {
    //     se.forEach((item, index) => {
    //       this.selectRow.push(this.noticeList.indexOf(item))
    //     })
    //   }
    // },
    // 高亮样式
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { 'background-color': 'rgba(185,221,249,.75)' }
      }
    },
    // 重置按钮功能
    resetQuery() {
      this.dateRange = []
      this.resetForm('formNotice')
      this.handleQuery()
    },
    // 搜索按钮操作
    handleQuery() {
      this.filters.pageNum = 1
      this.getList()
    },
    // 添加按钮
    handleAdd() {
      this.$router.push({
        path: '/PersonalOffice/message-add',
        query: {
          title: '新增公告'
        }
      })
    },
    // 修改按钮
    handleUpdate() {
      const noticeId = this.multipleSelection[0].noticeId
      this.$router.push({
        path: '/PersonalOffice/message-add',
        query: {
          title: '新增公告',
          noticeId: noticeId
        }
      })
    },
    handleStatus() {
      this.$confirm('是否变更状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await updateNoticeStatus(this.multipleSelection[0].noticeId)
        this.getList()
        this.msgSuccess('变更成功！')
      })
    },
    // 删除按钮
    handleDelete() {
      const child = this.multipleSelection
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // let noticeId = ''
        // for (let i = 0; i < child.length; i++) {
        //   noticeId += child[i].noticeId + ','
        // }
        // // 去掉最后一个逗号
        // if (noticeId.length > 0) {
        //   noticeId = noticeId.substr(0, noticeId.length - 1)
        // }
        await delNotice(child[0].noticeId)
        this.getList()
        this.msgSuccess('删除成功！')
      }).catch(() => {
        this.msgWarning('取消删除！')
      })
    },
    // 详情
    handleDetail() {
      const noticeId = this.multipleSelection[0].noticeId
      this.$router.push({
        path: '/PersonalOffice/message-detail',
        query: {
          title: '公告详情',
          noticeId: noticeId
        }
      })
    }
  }
}
</script>

<style scoped>
</style>
